package 堆.基础;

import java.util.Arrays;

public class MyHeap {
    int usedSize;
    int[] elem;

    public MyHeap() {
        this.elem = new int[10];
    }

    public void initHeap(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;//10
        }
    }

    //大堆
    public void createHeap(){
        //找出最大的根节点
        for (int i = (usedSize-1-1)/2; i >=0 ; i--) {
            shiftDown(i,usedSize);
        }
    }
    //向下调整
    public void shiftDown(int i ,int usedSize){
        int child = (i*2)+1;//左孩子
        while (child<usedSize) {
            if (child + 1 < elem.length && elem[child] < elem[child + 1]) {
                child++;
            }
            if (elem[child] > elem[i]) {
                swap(child,i);
                i = child;
                child = (i*2)+1;
            }else {
                break;
            }
        }
    }

    //插入
    public void offer(int val){
        if(isFull()){
            this.elem = Arrays.copyOf(elem,elem.length+1);
        }else {
            elem[usedSize] = val;
            shiftUp(usedSize);
            usedSize++;
        }
    }

    //向上调整
    public void shiftUp(int child){
        int parent = (child-1)/2;
        while (child>0) {
            if (elem[parent] < elem[child]) {
                swap(parent, child);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public int poll(){
        int tmp = elem[0];
        swap(0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);
        return tmp;
    }

    public boolean isFull(){
        return usedSize==elem.length;
    }

    public void  swap(int iIndex,int jIndex){
        int tmp = elem[iIndex];
        elem[iIndex] = elem[jIndex];
        elem[jIndex] = tmp;
    }

    public static void main(String[] args) {
        int[] array ={1,2,3,4,5,6,7,8,9};
        MyHeap myHeap =new MyHeap();
        myHeap.initHeap(array);
        myHeap.createHeap();
        System.out.println("==========");
        System.out.println("插入");
        myHeap.offer(10);
        System.out.println("==========");
        System.out.println("删除");
        int x = myHeap.poll();
        System.out.println(x);
    }
}
